/**
 * Created by yuzhou on 2017/7/10.
 */
import axios from 'axios'
import Qs from 'qs'

export const createInstance = () => {
  let instance = axios.create({
    baseURL: 'api/',
    timeout: 1000,
    paramsSerializer (params) {
      return Qs.stringify(params, {
        arrayFormat: 'brackets',
        allowDots: true
      })
    }
  })
  return instance
}

export const updateToken = (instance) => {
  let token = sessionStorage.getItem('token')
  if (token) {
    instance.defaults.headers.common['Authorization'] = 'Bearer ' + token
  } else {
    if (instance.defaults.headers.common['Authorization']) {
      delete instance.defaults.headers.common['Authorization']
    }
  }
}

export const procApiCb = (res, cb, errorCb) => {
  let rData = res.data
  if (rData.code === 0) {
    if (cb) {
      cb(rData['data'], rData['msg'])
    }
  } else {
    if (errorCb) {
      errorCb(rData['msg'], rData.code, rData['data'])
    } else {
      console.error(rData['msg'])
    }
  }
}

export const procApiError = (err, errorCb) => {
  if (errorCb) {
    errorCb(err['message'])
  } else {
    console.error(err)
  }
}
